//
//  BPLoginInViewController.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/10/26.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "BPLoginViewController.h"
#import "BPRegisterViewController.h"
#import "AccountTool.h"
#import "BPAccount.h"
#import "BPNavigationController.h"
#import "BPhttpTool.h"
#import "MBProgressHUD+MJ.h"
#import "MJExtension.h"
#import "AppDelegate.h"
#import "BPForgetPasswordViewController.h"
#import "BPHomeViewController.h"
#import "yunPicListVC.h"

#define messageBtnColor BPColor(244, 133, 142)

@interface BPLoginViewController ()<UITextFieldDelegate,UINavigationControllerDelegate,UIScrollViewDelegate>

@end

@implementation BPLoginViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self drawUIView];
    
    [self setUpAccountAndPassword];
}

- (void)setUpNav
{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(5.0f, 0, 50.0f, 50.0f);
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(dismissLogin) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:backBtn];
}

- (void)dismissLogin
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)drawUIView
{
    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    _scrollView.backgroundColor = [UIColor whiteColor];
    _scrollView.alwaysBounceVertical = YES;
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];
    
    [_scrollView addSubview:self.headView];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (UIView *)headView
{
    if (!_headView) {
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, 150.0f)];
        //_headView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LoginImage"]];
        
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(_headView.frame.size.width / 2 - 100, 0, 200, 140)];
        imageV.image = [UIImage imageNamed:@"LoginImage"];
        [_headView addSubview:imageV];
        
        UIImageView *langXian = [[UIImageView alloc] initWithFrame:CGRectMake(0, _headView.frame.size.height - 5, self.headView.frame.size.width, 5)];
        langXian.image = [UIImage imageNamed:@"波纹线"];
        [_headView addSubview:langXian];
        [self setUpNav];
        
    }
    return _headView;
}

- (void)setUpAccountAndPassword
{
    NSArray *placeArry = [NSArray arrayWithObjects:@"请输入您的手机号",@"请输入6~20位密码", nil];
    
    CGFloat textY = CGRectGetMaxY(_headView.frame);
    CGFloat textH = 47.0f;
    CGFloat textX = 20.0f;
    CGFloat textW = BPScreenW - 40.0f;
    
    UILabel *tele = [[UILabel alloc] initWithFrame:CGRectMake(textX, textY, 50, textH)];
    tele.text = @"账号:";
    tele.font = [UIFont systemFontOfSize:18];
    tele.alpha = 0.5;
    [_scrollView addSubview:tele];
    
    _phoneNmuber = [[UITextField alloc] initWithFrame:CGRectMake(textX + 50, textY, textW, textH)];
    _phoneNmuber.delegate = self;
    _phoneNmuber.keyboardType = UIKeyboardTypeNumberPad; 
    _phoneNmuber.placeholder = placeArry[0];
    NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:@"userPhone"];
    if (phone) {
        _phoneNmuber.text = phone;
    }
    [_scrollView addSubview:_phoneNmuber];
    
    
    
    UILabel *mima = [[UILabel alloc] initWithFrame:CGRectMake(textX, _phoneNmuber.y + textH, 50, textH)];
    mima.text = @"密码:";
    mima.font = [UIFont systemFontOfSize:18];
    mima.alpha = 0.5;
    [_scrollView addSubview:mima];
    
    /* 自定义开关按钮 */
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    button3.frame = CGRectMake(textX + 230, _phoneNmuber.y + textH + 5, 60, textH - 10);
    [_scrollView addSubview:button3];
    [button3 setImage:[UIImage imageNamed:@"BtnOff.png"] forState:UIControlStateNormal];
    [button3 addTarget:self action:@selector(button3Clicked:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _passWord = [[UITextField alloc] init];
    _passWord.secureTextEntry = YES;
//    _passWord.frame = _phoneNmuber.bounds;
    _passWord.frame = CGRectMake(textX + 50, textY, textW - 100, textH);
    _passWord.y = _phoneNmuber.y + textH;
    _passWord.x = textX + 50;
    _passWord.delegate = self;
    _passWord.placeholder = placeArry[1];
    [_scrollView addSubview:_passWord];
    
    _BPloginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_BPloginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self addBtnDengLu:_BPloginBtn];
    _BPloginBtn.frame = CGRectMake(25, _passWord.y + _passWord.height + 30, self.view.frame.size.width - 50, 30);
    //_BPloginBtn.center = CGPointMake(BPScreenW / 2.0, _passWord.y + _passWord.height + 30);
    [_BPloginBtn addTarget:self action:@selector(LoginIn) forControlEvents:UIControlEventTouchUpInside];
    
    _registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_registerBtn setTitle:@"快速注册" forState:UIControlStateNormal];
    _registerBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_registerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self addBtn:_registerBtn];
    _registerBtn.center = CGPointMake(BPScreenW / 5.0, _BPloginBtn.y + _BPloginBtn.height + 30.0f);
    [_registerBtn addTarget:self action:@selector(registerAccount2) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *forget = [UIButton buttonWithType:UIButtonTypeCustom];
    [forget setTitle:@"忘记密码?" forState:UIControlStateNormal];
    forget.titleLabel.font = [UIFont systemFontOfSize:14];
    [forget setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self addBtn:forget];
    forget.center = CGPointMake((BPScreenW * 0.8), _BPloginBtn.y + _BPloginBtn.height + 30.0f);
    [forget addTarget:self action:@selector(forgetPass) forControlEvents:UIControlEventTouchUpInside];
    
    for (int i = 0; i < 2; i ++) {
        BPLineView *line = [[BPLineView alloc] initWithFrame:CGRectMake(60, textY + textH * (i+1), BPScreenW, 0.7)];
        [_scrollView addSubview:line];
    }
}

- (void)forgetPass
{
    BPForgetPasswordViewController *forget = [[BPForgetPasswordViewController alloc] init];
    [self.navigationController pushViewController:forget animated:YES];
}

// button 的背景颜色
- (void)addBtn:(UIButton *)button
{
    button.size = CGSizeMake(106.0f, 32.0f);
   // button.backgroundColor = BPGlobaThemeColor;
    [button.layer setCornerRadius:16.0f];
    [_scrollView addSubview:button];
}

// 开关按钮 (显示不显示密码)
- (void)button3Clicked:(UIButton *)button
{
    button.selected = !button.selected;
    if (button.selected == YES) {    /* button.selected也可以写成 button.isSelected */
        
        [button setImage:[UIImage imageNamed:@"BtnOn.png"] forState:UIControlStateNormal];
        _passWord.secureTextEntry = NO;
        
    }else if (button.selected == NO)
    {
        [button setImage:[UIImage imageNamed:@"BtnOff.png"] forState:UIControlStateNormal];
        
        _passWord.secureTextEntry = YES;
    }
}

// 登录的按钮有背景
- (void)addBtnDengLu:(UIButton *)button
{
    button.size = CGSizeMake(106.0f, 32.0f);
    button.backgroundColor = BPGlobaThemeColor;
    [button.layer setCornerRadius:16.0f];
    [_scrollView addSubview:button];
}

- (void)LoginIn
{
    if ([self checkPhoneNumber] == YES && [self isStrEmpty:_passWord.text] == NO) {
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"正在登录"];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setValue:_phoneNmuber.text forKey:@"username"];
        [param setValue:_passWord.text forKey:@"password"];
        [BPhttpTool post:[NSString stringWithFormat:@"%@user/login",BPhttp] params:param success:^(id responseObj) {
            NSDictionary *dic = responseObj;

            if ([dic[@"uid"] intValue] == -1) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"该手机号码未注册，请先注册"];
            }else{
                
                
                hud.removeFromSuperViewOnHide = YES;
                [hud setHidden:YES];
                if ([dic[@"uid"] intValue] > 0) {
                    BPAccount *account = [BPAccount objectWithKeyValues:responseObj[@"info"]];
                    
                    [AccountTool save:account];
                    
                    [[NSUserDefaults standardUserDefaults] setObject:account.mobile forKey:@"userPhone"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    [[NSUserDefaults standardUserDefaults] setObject:_passWord.text forKey:@"passWord"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    _block();
                    
                }else{
                    
                    [MBProgressHUD showError:@"密码错误"];
                }
            }
        } failure:^(NSError *error) {
            hud.removeFromSuperViewOnHide = YES;
            [hud setHidden:YES];
            [MBProgressHUD showError:@"登入失败"];
        }];
    }
}

- (void)registerAccount2
{
    BPRegisterViewController *registerA = [[BPRegisterViewController alloc] init];
    registerA.isHome = _isHome;
    [self.navigationController pushViewController:registerA animated:YES];
    registerA.regblock = ^(){
        _block();
    };
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offsetY = frame.origin.y + frame.size.height - (self.view.frame.size.height - 320.0);
    if (offsetY > 0) {
        [UIView animateWithDuration:0.3f animations:^{
            self.view.frame = CGRectMake(0, -offsetY, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
    [UIView commitAnimations];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame =  CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (BOOL)checkPhoneNumber
{
    NSString *phoneNumber = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumber];
    
    BOOL isMatch = [pred evaluateWithObject:_phoneNmuber.text];
    
    if (!isMatch) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入正确的手机号码" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }else
    {
        return YES;
    }
}

-(BOOL)isStrEmpty:(NSString*)str
{
    if (str == nil || str == NULL)
    {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    if ([str length] <= 0)
    {
        return YES;
    }
    return NO;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
